package com.itheima.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    //获取验证码
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //1.获取手机号
        String phone = user.getPhone();
        //2.生成验证码
        String code = RandomUtil.randomNumbers(2);
        System.out.println("验证码：" + code);
        //给手机发送验证码
        //SMSUtils2.sendSms(phone,code);
//        session.setAttribute("phone", phone);
//        session.setAttribute("code", code);
        //
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return R.success("验证码发送成功");
    }

    //登录验证码
    @PostMapping("/login")
    public R<String> login(@RequestBody Map map, HttpSession session) {
        //获取手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //对比用户从输入的验证码和存储的验证码
        Object o = redisTemplate.opsForValue().get(phone);
        if (o!=null &&o.equals(code)) {
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getPhone, phone);
            User user = userService.getOne(qw);
            //判断用户名是否存在
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                //在表中保存用户手机号
                userService.save(user);
                //在session中保存表中生成的id
            }
            session.setAttribute("loginPhoneId",user.getId());
            redisTemplate.delete(phone);
            return R.success("登陆成功");
        }
        return R.error("用户名或密码错误");
    }

    //退出登录
    @PostMapping("/{loginout}")
    public R logout(HttpSession session){
        session.removeAttribute("loginPhoneId");
        return R.success("退出成功");
    }
}
